package com.example.ai.service;

import com.baidu.aip.ocr.AipOcr;
import com.example.ai.config.BaiduOcrConfig;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;

@Service
public class BaiduOcrService {
    private final AipOcr client;

    public BaiduOcrService(BaiduOcrConfig config) {
        this.client = new AipOcr(config.getAppId(), config.getApiKey(), config.getSecretKey());
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
    }

    public String recognizeText(MultipartFile file) {
        try {
            // 传入可选参数
            HashMap<String, String> options = new HashMap<>();
            options.put("language_type", "CHN_ENG"); // 中英文混合
            options.put("detect_direction", "true"); // 检测方向
            options.put("detect_language", "true"); // 检测语言
            options.put("probability", "true"); // 返回识别结果中每一行的置信度

            // 调用通用文字识别接口
            JSONObject response = client.basicGeneral(file.getBytes(), options);
            
            // 解析结果
            StringBuilder result = new StringBuilder();
            response.getJSONArray("words_result").forEach(item -> {
                JSONObject word = (JSONObject) item;
                result.append(word.getString("words")).append("\n");
            });
            
            return result.toString();
        } catch (Exception e) {
            throw new RuntimeException("OCR识别失败", e);
        }
    }
} 